package cn.lili.modules.store.serviceimpl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.common.enums.DictCodeEnum;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.properties.RocketmqCustomProperties;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.*;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.goods.entity.dos.Category;
import cn.lili.modules.goods.mapper.CategoryMapper;
import cn.lili.modules.goods.service.GoodsService;
import cn.lili.modules.member.entity.dos.Extension;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.dto.CollectionDTO;
import cn.lili.modules.member.entity.enums.PartnerStatusEnum;
import cn.lili.modules.member.entity.vo.GradeLevelVO;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.*;
import cn.lili.modules.member.serviceimpl.ExtensionServiceImpl;
import cn.lili.modules.message.entity.dos.RollMessage;
import cn.lili.modules.message.mapper.RollMessageMapper;
import cn.lili.modules.permission.entity.dos.Menu;
import cn.lili.modules.permission.entity.dos.Role;
import cn.lili.modules.permission.entity.dos.RoleMenu;
import cn.lili.modules.permission.entity.dos.StoreUser;
import cn.lili.modules.permission.service.MenuService;
import cn.lili.modules.permission.service.RoleMenuService;
import cn.lili.modules.permission.service.RoleService;
import cn.lili.modules.permission.service.StoreUserService;
import cn.lili.modules.store.entity.dos.FreightTemplate;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.dos.StoreDetail;
import cn.lili.modules.store.entity.dto.*;
import cn.lili.modules.store.entity.enums.StoreStatusEnum;
import cn.lili.modules.store.entity.vos.StoreAddrDetailVO;
import cn.lili.modules.store.entity.vos.StoreSearchParams;
import cn.lili.modules.store.entity.vos.StoreVO;
import cn.lili.modules.store.mapper.StoreMapper;
import cn.lili.modules.store.service.FreightTemplateService;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.system.entity.dos.Logistics;
import cn.lili.modules.system.entity.dos.RegionDetail;
import cn.lili.modules.system.mapper.RegionMapper;
import cn.lili.modules.system.service.LogisticsService;
import cn.lili.modules.system.service.RegionDetailService;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.dos.MemberWithdrawApply;
import cn.lili.modules.wallet.entity.dto.MemberWithdrawalMessage;
import cn.lili.modules.wallet.entity.enums.MemberWithdrawalDestinationEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.entity.enums.WithdrawStatusEnum;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.wallet.service.MemberWithdrawApplyService;
import cn.lili.modules.wallet.service.WalletDetailService;
import cn.lili.modules.whitebar.entity.dos.RateSetting;
import cn.lili.modules.whitebar.service.RateSettingService;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.rocketmq.RocketmqSendCallbackBuilder;
import cn.lili.rocketmq.tags.MemberTagsEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 店铺业务层实现
 *
 * @author pikachu
 * @since 2020-03-07 16:18:56
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

	private Logger log = LoggerFactory.getLogger(StoreServiceImpl.class);

	@Autowired
	private MenuService menuService;

	@Autowired
	private StoreUserService storeUserService;
	@Autowired
	private RoleService roleService;
	/**
	 * 会员
	 */
	@Autowired
	private MemberService memberService;
	/**
	 * 菜单角色
	 */
	@Autowired
	private RoleMenuService roleMenuService;
	/**
	 * 商品
	 */
	@Autowired
	private GoodsService goodsService;
	/**
	 * 店铺详情
	 */
	@Autowired
	private StoreDetailService storeDetailService;

	@Autowired
	private LogisticsService logisticsService;

	@Autowired
	private StoreLogisticsService storeLogisticsService;

	@Autowired
	private CategoryMapper categoryMapper;
	@Autowired
	private PartnerMapper partnerMapper;

	@Autowired
	private RateSettingService rateSettingService;

	@Autowired
	private EextensionService eextensionService;

	@Autowired
	private ExtensionServiceImpl extensionService;

	@Autowired
	private RollMessageMapper rollMessageMapper;

	@Autowired
	private MemberWalletService memberWalletService;

	@Autowired
	private WalletDetailService walletDetailService;

	@Autowired
	private FreightTemplateService freightTemplateService;
	@Autowired
	private PartnerService partnerService;

	@Autowired
	private RegionMapper regionMapper;

	@Autowired
	private RegionService regionService;

	@Autowired
	private RegionDetailService regionDetailService;

	@Autowired
	private RocketmqCustomProperties rocketmqCustomProperties;
	@Autowired
	private RechargeFowService rechargeFowService;

	@Autowired
	private MemberWithdrawApplyService memberWithdrawApplyService;
	@Autowired
	private RocketMQTemplate rocketMQTemplate;
	@Override
	public IPage<StoreVO> findByConditionPage(StoreSearchParams storeSearchParams, PageVO page) {
		storeSearchParams.setOrderBySort(true);
		QueryWrapper queryWrapper = storeSearchParams.queryWrapper();
		// 根据code查询合伙人管理的区域Code
		if (StringUtils.isNotEmpty(storeSearchParams.getAdCode())) {
			List itemAdCod = regionService.getPartnerAdCode(storeSearchParams.getAdCode(), "4");
			queryWrapper.in("s.ad_code", itemAdCod);
		}
		return this.baseMapper.getStoreList(PageUtil.initPage(page), queryWrapper,
				storeSearchParams.getOrderStartDate(), storeSearchParams.getOrderEndDate());
	}

	@Override
	public IPage<StoreVO> findByConditionPageShenhe(StoreSearchParams storeSearchParams, PageVO page) {
		storeSearchParams.setOrderBySort(true);
		QueryWrapper queryWrapper = storeSearchParams.queryWrapper();
		// 根据code查询合伙人管理的区域Code
		if (StringUtils.isNotEmpty(storeSearchParams.getAdCode())) {
			List itemAdCod = regionService.getPartnerAdCode(storeSearchParams.getAdCode(), "4");
			queryWrapper.in("s.ad_code", itemAdCod);
		}
		return this.baseMapper.findByConditionPageShenhe(PageUtil.initPage(page), queryWrapper);
	}

	@Override
	public IPage<StoreVO> getAbnormalStoreByPage(StoreSearchParams storeSearchParams, PageVO page) {
		storeSearchParams.setStoreDisable(StoreStatusEnum.LOGOUT.value());
		storeSearchParams.setOrderBySort(true);
		return this.baseMapper.getStoreList(PageUtil.initPage(page), storeSearchParams.queryWrapper(),
				storeSearchParams.getOrderStartDate(), storeSearchParams.getOrderEndDate());
	}

	@Override
	public IPage<StoreVO> getStoreListByPage(StoreSearchParams storeSearchParams, PageVO page) {
		return this.baseMapper.getStoreListByPage(PageUtil.initPage(page), storeSearchParams.getStoreId());
	}

	@Override
	public StoreVO getStoreDetail() {
		AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
		StoreVO storeVO = this.baseMapper.getStoreDetail(currentUser.getMemberId());
		storeVO.setNickName(currentUser.getNickName());
		return storeVO;
	}

	@Override
	public Store add(AdminStoreApplyDTO adminStoreApplyDTO) {
		// 判断店铺名称是否存在
		QueryWrapper<Store> queryWrapper = Wrappers.query();
		queryWrapper.eq("store_name", adminStoreApplyDTO.getStoreName());
		queryWrapper.eq("store_disable", "OPEN");
		if (this.getOne(queryWrapper) != null) {
			throw new ServiceException(ResultCode.STORE_NAME_EXIST_ERROR);
		}
		Member member = memberService.getById(adminStoreApplyDTO.getMemberId());
		// 判断用户是否存在
		if (member == null) {
			throw new ServiceException(ResultCode.USER_NOT_EXIST);
		}
		Store store = new Store(member, adminStoreApplyDTO);
		StoreDetail storeDetail = new StoreDetail(store, adminStoreApplyDTO);
		// 判断商品是否初审
		String memberId = member.getId();
		QueryWrapper<Extension> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("member_id", memberId);
		objectQueryWrapper.eq("delete_flag", false);
		List<Extension> list = eextensionService.list(objectQueryWrapper);
		if (list.size() > 0) {
			Extension extension = list.get(0);
			Member promotionCode = memberService
					.getOne(new QueryWrapper<Member>().eq("promotion_code", extension.getExtension()));
			if (promotionCode != null) {
				QueryWrapper<Partner> partnersWrapper = new QueryWrapper<>();
				partnersWrapper.eq("member_id", promotionCode.getId()); // 推广人Id
				partnersWrapper.eq("delete_flag", false);
				List<Partner> partners = partnerService.list(partnersWrapper);
				if (partners.size() > 0) {
					Integer partnerType = partners.get(0).getPartnerType();
					if (partnerType != null && partnerType == 1 || partnerType == 4) {
						store.setStoreDisable(StoreStatusEnum.FIRSTTRIAL.name()); // 初审
					}
				}
			}
		}
		// 判断是否有历史店铺数据
		 List<Store> memberIds = this.list(new QueryWrapper<Store>().eq("member_id",
		 memberId));
		 if (memberIds.size() > 0) {
			 this.deleteByMemberId(memberId);
		 }
		 // 更新店铺信息
		// QueryWrapper<Store> queryWrapperStore = Wrappers.query();
		// queryWrapperStore.eq("store_disable", "OPEN");
		// queryWrapperStore.eq("member_id", adminStoreApplyDTO.getMemberId());
		// if (this.getOne(queryWrapperStore) != null) {
		// throw new ServiceException(ResultCode.STORE_APPLY_DOUBLE_ERROR);
		// }
		// store.setId(member.getStoreId());
		//
		// // 先去更新detail表
		// QueryWrapper<StoreDetail> queryWrapperStoreOther = Wrappers.query();
		// queryWrapperStoreOther.eq("store_id", member.getStoreId());
		// StoreDetail storeDetailServiceOne =
		// storeDetailService.getOne(queryWrapperStoreOther);
		// storeDetail.setId(storeDetailServiceOne.getId());
		// store.setAdCode(adminStoreApplyDTO.getChooseCode());
		// this.updateById(store);
		// storeDetailService.updateById(storeDetail);
		// } else {
		// 新增店铺信息
		store.setAdCode(adminStoreApplyDTO.getChooseCode());
		this.save(store);
		StoreDetail storeDetailOther = new StoreDetail(store, adminStoreApplyDTO);
		// 添加店铺
		storeDetailService.save(storeDetailOther);
		// }
		// 设置会员-店铺信息
		memberService.update(new LambdaUpdateWrapper<Member>().eq(Member::getId, member.getId())
				.set(Member::getHaveStore, false).set(Member::getStoreId, store.getId()).set(Member::getLocation, store.getAdCode()));
		return store;
	}

	@Override
	public Store edit(StoreEditDTO storeEditDTO) {
		if (storeEditDTO != null) {
			// 判断店铺名是否唯一
			Store storeTmp = getOne(new QueryWrapper<Store>().eq("store_name", storeEditDTO.getStoreName())
					.eq(StringUtils.isNotEmpty(storeEditDTO.getStoreId()), "id", storeEditDTO.getStoreId()));
			if (storeTmp != null && !CharSequenceUtil.equals(storeTmp.getId(), storeEditDTO.getStoreId())) {
				throw new ServiceException(ResultCode.STORE_NAME_EXIST_ERROR);
			}
			// 修改店铺详细信息
			updateStoreDetail(storeEditDTO);
			// 修改店铺信息
			return updateStore(storeEditDTO);
		} else {
			throw new ServiceException(ResultCode.STORE_NOT_EXIST);
		}
	}

	/**
	 * 修改店铺基本信息
	 *
	 * @param storeEditDTO
	 *            修改店铺信息
	 */
	private Store updateStore(StoreEditDTO storeEditDTO) {
		log.info("是否有合同0,参数为{}", storeEditDTO.getIsHaveContract());
		Store store = this.getById(storeEditDTO.getStoreId());
		log.info("是否有合同1,参数为{}", store.getIsHaveContract());
		if (store != null) {
			BeanUtil.copyProperties(storeEditDTO, store);
			log.info("是否有合同2,参数为{}", store.getIsHaveContract());
			store.setId(storeEditDTO.getStoreId());
			boolean result = this.updateById(store);
			if (result) {
				storeDetailService.updateStoreGoodsInfo(store);
			}
			// 修改位置
			memberService.update(new LambdaUpdateWrapper<Member>().eq(Member::getId, store.getMemberId())
				.set(Member::getLocation, store.getAdCode()));
		}
		return store;
	}

	/**
	 * 修改店铺详细细腻
	 *
	 * @param storeEditDTO
	 *            修改店铺信息
	 */
	private void updateStoreDetail(StoreEditDTO storeEditDTO) {
		StoreDetail storeDetail = new StoreDetail();
		BeanUtil.copyProperties(storeEditDTO, storeDetail);
		storeDetailService.update(storeDetail,
				new QueryWrapper<StoreDetail>().eq("store_id", storeEditDTO.getStoreId()));
	}

	@Override
	public boolean audit(String id, Integer passed, String causer) {
		Store store = this.getById(id);
		if (store == null) {
			throw new ServiceException(ResultCode.STORE_NOT_EXIST);
		}
		log.info("店铺信息: {}", JSONUtil.toJsonStr(store));
		if (passed == 0) {
			store.setStoreDisable(StoreStatusEnum.OPEN.value());
			store.setStoreAuditTime(new Date());

			// 修改会员 表示已有店铺
			Member member = memberService.getById(store.getMemberId());
			member.setHaveStore(true);
			member.setStoreId(id);
			member.setType(1);
			memberService.updateById(member);
			// 设定商家的结算日
			storeDetailService.update(new LambdaUpdateWrapper<StoreDetail>().eq(StoreDetail::getStoreId, id)
					.set(StoreDetail::getSettlementDay, new DateTime()));
			// 批量添加物流公司
			List<Logistics> logistics = logisticsService.list();
			if (CollectionUtils.isNotEmpty(logistics)) {
				logistics.forEach(logistics1 -> {
					storeLogisticsService.add(logistics1.getId(), store.getId());
				});
			}
			// 自动成为天使合伙人
			MemberVO member0 = memberService.getUserInfos("BUYER", member.getUsername());
			Partner partner = new Partner();
			if (member0.getPartnerType() != null) {
				// 充值前先把原有的合伙人信息禁用
				partnerMapper.updateByMemberId(member.getId());
			}
			// 获取时间加一年或加一月或加一天
			Date date = new Date();
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);// 设置起时间
			cal.add(Calendar.YEAR, 3);// 增加一年
			partner.setBeginTime(date);
			partner.setEndTime(cal.getTime());
			partner.setMemberId(member.getId());
			partner.setPartnerState(0);
			partner.setPartnerType(0);
			List<RateSetting> rateSettingVOS = rateSettingService.list(new QueryWrapper<>());
			if (CollectionUtils.isNotEmpty(rateSettingVOS)) {
				for (RateSetting rateSetting : rateSettingVOS) {
					if ("天使合伙人".equals(rateSetting.getRoleName())) {
						// 商家自动成为天使合伙人
						partner.setPartnerType(2);
						partner.setRoleId(rateSetting.getRoleId());
					}
				}
			}
			partner.setAuditState(PartnerStatusEnum.PASS.name());
			partner.setRegion(store.getStoreAddressPath());
			if (StringUtils.isEmpty(store.getAdCode()) || "null".equals(store.getAdCode())) {
				String[] split = store.getStoreAddressIdPath().split(",");
				List<Map<String, Object>> itemAdCod = regionMapper.getItemAdCod(split[split.length - 1]);
				if (itemAdCod != null && itemAdCod.get(0) != null)
					store.setAdCode((String) itemAdCod.get(0).get("adCode"));
			}
			partner.setRegionId(store.getAdCode());
			partner.setPayState(1);

			QueryWrapper partnerQ = new QueryWrapper();
			partnerQ.eq("partner_type", 2);
			partnerQ.orderByDesc("create_time");
			partnerQ.last("limit 1");
			Partner partner2 = this.partnerMapper.selectOne(partnerQ);
			partner.setCode(partner2.getCode() + 1);
			partner.setPrefix("BHSQ-TSHHR03-");
			partnerMapper.insert(partner);
			// 添加推广码
			Member member1 = memberService.getById(member.getId());
			member1.setId(member.getId());
			if (StringUtils.isEmpty(member.getPromotionCode())) {
				member1.setPromotionCode(eextensionService.getExtension());
			}
			// 绑定店铺和事业合伙人
			log.info("店铺审核通过 开始绑定B端 和 事业合伙人 {}", member.getId());
			eextensionService.tempExToEx(member.getId(), false);

			member1.setExtensionFlag(Boolean.FALSE);

			// 保留变更记录
			RegionDetail regionDetail = new RegionDetail();
			regionDetail.setMemberId(id);
			regionDetail.setBeforeAdCode(member1.getLocation());
			regionDetail.setBeforeName(regionService.getItemAdCodOrName(member1.getLocation()));
			regionDetail.setAfterAdCode(store.getAdCode());
			regionDetail.setAfterName(regionService.getItemAdCodOrName(store.getAdCode()));
			regionDetailService.save(regionDetail);

			// 店铺区域修改个人区域
			member1.setLocation(store.getAdCode());
			memberService.updateById(member1);

			// 在滚动消息里添加数据
			RollMessage rollMessage = new RollMessage();
			// Member member = memberService.getById(memberId);
			rollMessage.setContent(member.getNickName() + "的店铺审核通过");
			rollMessage.setCreateBy(member.getId());
			rollMessage.setCreateTime(new Date());
			rollMessage.setType(3);
			rollMessage.setStatus(1);
			rollMessage.setDelFlag(false);
			rollMessage.setId(String.valueOf(SnowFlake.getId()));
			boolean save = rollMessageMapper.insert(rollMessage) > 0;
			// 创建店铺角色
			Role role = this.saveRole(store);
			// 创建角色对应的菜单
			this.roleMenu(role);
			// 创建店铺账户
			this.saveRoleUser(store, member, role.getId());
			// 添加默认包邮模板
			this.saveFreightTemplate(store);
		} else {
			store.setStoreDisable(StoreStatusEnum.REFUSED.value());
			store.setCauser(causer);
		}
		return this.updateById(store);
		// //REFUSED 审核拒绝 OPEN 店铺开启 CLOSED("店铺关闭"), APPLYING("申请中，提交审核");
		// List<Store> list = this.list();
		// list.forEach(store -> {
		// if (store.getStoreDisable().equals("OPEN") ||
		// store.getStoreDisable().equals("CLOSED")) {
		// Member member = memberService.getById(store.getMemberId());
		// if (member != null) {
		// //创建店铺角色
		// Role role = this.saveRole(store);
		// //创建角色对应的菜单
		// this.roleMenu(role);
		// //创建店铺账户
		// this.saveRoleUser(store, member, role.getId());
		// //添加默认包邮模板
		// this.saveFreightTemplate(store);
		// } else {
		// System.out.println("11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111%%%%%"
		// + store.getId() + "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		// }
		// }
		// });
		// return true;

	}

	/**
	 * 创建默认包邮模板
	 */
	private void saveFreightTemplate(Store store) {
		FreightTemplate freightTemplate = new FreightTemplate();
		freightTemplate.setName("包邮");
		freightTemplate.setPricingMethod("FREE");
		freightTemplate.setStoreId(store.getId());
		freightTemplateService.save(freightTemplate);
	}

	/**
	 * 创建角色管理的菜单
	 */
	private void roleMenu(Role role) {
		QueryWrapper<Menu> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("state", "1");
		List<Menu> list = menuService.list(objectQueryWrapper);
		list.forEach(item -> {
			RoleMenu roleMenu = new RoleMenu();
			roleMenu.setRoleId(role.getId()); // 角色Id
			roleMenu.setMenuId(item.getId());// 菜单Id
			roleMenu.setCreateBy(UserContext.getCurrentUser().getUsername());
			roleMenu.setCreateTime(new Date());
			roleMenuService.save(roleMenu);
		});
	}

	/**
	 * 创建店铺角色
	 */
	private Role saveRole(Store store) {
		Role roleNew = new Role();
		// 创建角色
		roleNew.setName(UserEnums.STORE.getRole());
		roleNew.setRoleName(store.getStoreName() + "店铺角色");
		roleNew.setCreateBy(UserContext.getCurrentUser().getUsername());
		roleNew.setCreateTime(new Date());
		roleNew.setParentId("0"); // 初始化一级菜单
		roleNew.setAncestors(",0"); // 初始化一级菜单
		roleNew.setSortOrder(0);
		roleNew.setState("1"); // 0平台角色 1商家角色
		roleService.save(roleNew);
		return roleNew;
	}

	/**
	 * 创建商家用户
	 */
	private void saveRoleUser(Store store, Member member, String roleId) {
		QueryWrapper<StoreUser> objectQueryWrapper = new QueryWrapper<>();
		objectQueryWrapper.eq("username", member.getUsername());
		StoreUser one = storeUserService.getOne(objectQueryWrapper);
		if (one != null) {
			throw new ServiceException(ResultCode.STORE_APPLY_DOUBLE_ERROR);
		}
		StoreUser storeUser1 = new StoreUser(); // 将该商家存到商家表中
		storeUser1.setCreateTime(new Date()); // 创建时间
		storeUser1.setAvatar(member.getFace()); // 用户头像
		storeUser1.setStoreLogo(store.getStoreLogo());// 店铺logo
		storeUser1.setMobile(member.getMobile()); // 手机号
		storeUser1.setNickName(member.getNickName()); // 昵称
		storeUser1.setPassword(member.getPassword()); // 密码
		storeUser1.setUsername(member.getUsername()); // 用户名
		storeUser1.setStoreId(store.getId());// 店铺Id
		storeUser1.setMemberId(member.getId()); // 会员Id
		storeUser1.setRoleIds(roleId); // 角色Id
		storeUser1.setIsSuper(true);// 是否是超级管理员 超级管理员/普通管理员
		storeUserService.save(storeUser1);
	}

	@Override
	public boolean disable(String id, String num) {
		Store store = this.getById(id);
		if (store != null) {
			store.setStoreDisable(StoreStatusEnum.LOGOUT.value());
			store.setClosingReturnAmount(StringUtils.isNotEmpty(num) ? Double.parseDouble(num) : 0);
			// 下架所有此店铺商品
			goodsService.underStoreGoods(id);
			// 解绑下级人员名单
			Member member = memberService.getById(store.getMemberId());
			if (member == null) {
				log.error("撤销合伙人-未检测到会员数据 入参memberId：{}", store.getMemberId());
				return Boolean.FALSE;
			}
			// 删除商家pc端账号
			QueryWrapper<StoreUser> queryWrapper = new QueryWrapper();
			queryWrapper.eq("mobile", member.getMobile());
			storeUserService.remove(queryWrapper);
			// 解绑下级会员,释放下级会员可绑定关系;
			eextensionService.updateByExtensionCode(member.getPromotionCode());
			// 更新会员有店铺标识/可绑定状态
			// member.setHaveStore(false);
			// member.setExtensionFlag(Boolean.TRUE);
			// member.setStoreId(null);
			// memberService.updateById(member);
			LambdaUpdateWrapper<Member> memberLambdaUpdateWrapper = Wrappers.<Member>lambdaUpdate();
			memberLambdaUpdateWrapper.set(Member::getHaveStore, false).set(Member::getExtensionFlag, Boolean.TRUE)
					.set(Member::getStoreId, null).eq(Member::getId, member.getId());
			memberService.update(memberLambdaUpdateWrapper);
			// 解绑与上级的关系;
			List l = new ArrayList<>();
			l.add(member.getId());
			extensionService.updateBymemberId(l);
			// 清空钱包
			// 根据会员Id查询所有的钱包
			List<MemberWallet> memberWalletById = memberWalletService.getMemberWalletById(store.getMemberId());
			if (memberWalletById.size() > 0) {
				AtomicReference<Double> TotalRecoveredSale = new AtomicReference<>(0.0);
				AtomicReference<Double> TotalRecoveredPromote = new AtomicReference<>(0.0);
				AtomicReference<Double> TotalRecovered = new AtomicReference<>(0.0);
				memberWalletById.forEach(intm -> {
					if (intm.getMemberWallet() == null
							|| intm.getMemberWallet().compareTo(Double.parseDouble("0")) == 0) {
						return;
					}
					Double wallet = intm.getMemberWallet() == null ? 0.00 : intm.getMemberWallet();
					if (!StringUtils.equals("RECHARGE", intm.getOwner())) {
						applyWithdrawal(store.getMemberId(),wallet, intm.getOwner(),num);
					}
					intm.setMemberWallet(0.0);
					switch (intm.getOwner()) {
						case "SALE" : // 销售钱包余额
							TotalRecoveredSale.updateAndGet(v -> v + wallet);
							memberWalletService.updateById(intm);
							break;
						case "PROMOTE" : // 推广钱包余额
							memberWalletService.updateById(intm);
							TotalRecoveredPromote.updateAndGet(v -> v + wallet);
							break;
						case "PROMOTE_FW" :// 推广会员费钱包余额
							TotalRecoveredPromote.updateAndGet(v -> v + wallet);
							memberWalletService.updateById(intm);
							break;
						case "PROMOTE_HY" :// 推广服务费钱包余额
							TotalRecoveredPromote.updateAndGet(v -> v + wallet);
							memberWalletService.updateById(intm);
							break;
					}
				});
				TotalRecovered.updateAndGet(v -> v + TotalRecoveredSale.get() + TotalRecoveredPromote.get());
				store.setTotalRecoveredSale(Double.parseDouble(TotalRecoveredSale.toString()));
				store.setTotalRecoveredPromote(Double.parseDouble(TotalRecoveredPromote.toString()));
				store.setTotalRecovered(Double.parseDouble(TotalRecovered.toString()));
			}
			// 作废合伙人
			partnerMapper.updateByMemberId(store.getMemberId());
			// 更改店铺状态 更改店铺退回金额;
			store.setStoreEndTime(new Date());
			boolean flag = this.updateById(store);
			return flag;
		}
		throw new ServiceException(ResultCode.STORE_NOT_EXIST);
	}

	public MemberWithdrawApply applyWithdrawal(String memberId,Double price, String owner,String num) {
		MemberWithdrawalMessage memberWithdrawalMessage = new MemberWithdrawalMessage();
		AuthUser authUser = UserContext.getCurrentUser();
		String nickName = authUser.getNickName();
		if(memberId != null) {
			Member m = memberService.getById(memberId);
			if(m != null)
				nickName = m.getNickName();
		}
		// 构建审核参数
		MemberWithdrawApply memberWithdrawApply = new MemberWithdrawApply();
		memberWithdrawApply.setMemberId(memberId != null ? memberId : authUser.getId());
		memberWithdrawApply.setMemberName(nickName);
		memberWithdrawApply.setApplyPrice(price);
		memberWithdrawApply.setOwner(owner);
		String remark = "";
		// 计算实际到账金额和手续费
		String member = memberService.findByPartner(memberId != null ? memberId : authUser.getId());
		String dictText = member;
		String value = "";
		try {
			switch (owner) {
				case "PROMOTE_HY" : {
					remark = "推广钱包";
					value = SysDictUtils.getValueString(DictCodeEnum.PROMOTE_WITHDRAWAL_RATE.dictCode(), dictText);
					break;
				}
				case "PROMOTE_FW" : {
					remark = "推广钱包";
					value = SysDictUtils.getValueString(DictCodeEnum.PROMOTE_WITHDRAWAL_RATE.dictCode(), dictText);
					break;
				}
				case "PROMOTE" : {
					remark = "推广钱包";
					value = SysDictUtils.getValueString(DictCodeEnum.PROMOTE_WITHDRAWAL_RATE.dictCode(), dictText);
					break;
				}
				case "SALE" : {
					remark = "销售钱包";
					value = SysDictUtils.getValueString(DictCodeEnum.SALE_WITHDRAWAL_RATE.dictCode(), dictText);
					break;
				}
				default :
					break;
			}
			if (StringUtils.isEmpty(value)) {
				throw new ServiceException(ResultCode.DICT_LI_NAME_NO_EXIST);
			}
		} catch (Exception e) {
			throw new ServiceException(ResultCode.DICT_LI_NAME_NO_EXIST);
		}

		Double realMoney = CurrencyUtil.mul(Double.parseDouble(value), price);
		memberWithdrawApply.setApplyMoney(realMoney);
		memberWithdrawApply.setHandlingMoney(CurrencyUtil.sub(price, realMoney));
		memberWithdrawApply.setFee(Double.parseDouble(value));
		memberWithdrawalMessage.setRealMoney(realMoney);
		memberWithdrawalMessage.setHandlingMoney(CurrencyUtil.sub(price, realMoney));
		memberWithdrawApply.setApplyStatus(WithdrawStatusEnum.CLOSE_FINISH.name());
		String sn = "W" + SnowFlake.getId();
		memberWithdrawApply.setSn(sn);
		memberWithdrawalMessage.setStatus(WithdrawStatusEnum.CLOSE_FINISH.name());
		MemberWallet from = memberWalletService.getMemberWalletInfo(memberId != null ? memberId : authUser.getId(), owner);
		MemberWallet admin = memberWalletService.getMemberWalletInfo("admin", WalletOwnerEnum.RECHARGE.name(), "平台");// 平台消费钱包

		memberWithdrawApply.setBeforeMoney(from.getMemberWallet());
		memberWalletService.withdrawApply(sn, from, admin, price, remark + "关闭店铺余额提现");

		// 推广钱包-会员费 提现
		if (owner.equals(WalletOwnerEnum.PROMOTE_HY.name())) {
			Map<String, Object> stringObjectMap = rechargeFowService.updatePromote(sn, price,memberId != null ? memberId : authUser.getId(), "21");
			memberWithdrawApply.setApplyPrice(Double.valueOf(stringObjectMap.get("alreadyPrice").toString()));// 申请提现焕呗额
			memberWithdrawApply.setApplyMoney(Double.parseDouble(stringObjectMap.get("alreadyMoney").toString()));// 申请提现现金额
			memberWithdrawApply.setFee(Double.parseDouble(stringObjectMap.get("fee").toString()));// 提现费率
			memberWithdrawApply.setHandlingMoney(Double.parseDouble(stringObjectMap.get("colPrice").toString()));// 手续费
			memberWithdrawApply.setWithholdingAdvance(
					memberWalletService.withholdingAdvance(Double.parseDouble(stringObjectMap.get("alreadyMoney").toString())));// 预扣预缴税额
		}
		// 销售 提现
		if (owner.equals(WalletOwnerEnum.SALE.name())) {
			Map<String, Object> stringObjectMap = memberWithdrawApplyService.txList(price, sn, memberId != null ? memberId : authUser.getId(), "11");
			memberWithdrawApply.setApplyPrice(Double.valueOf(stringObjectMap.get("alreadyPrice").toString()));// 申请提现焕呗额
			memberWithdrawApply.setApplyMoney(Double.parseDouble(stringObjectMap.get("alreadyMoney").toString()));// 申请提现现金额
			memberWithdrawApply.setFee(Double.parseDouble(stringObjectMap.get("fee").toString()));// 提现费率
			memberWithdrawApply.setHandlingMoney(Double.parseDouble(stringObjectMap.get("colPrice").toString()));// 手续费
		}
		// 发送余额提现申请消息
		memberWithdrawalMessage.setMemberId(memberId != null ? memberId : authUser.getId());
		memberWithdrawalMessage.setPrice(price);
		memberWithdrawalMessage.setDestination(MemberWithdrawalDestinationEnum.WECHAT.name());
		String destination = rocketmqCustomProperties.getMemberTopic() + ":" + MemberTagsEnum.MEMBER_WITHDRAWAL.name();
		rocketMQTemplate.asyncSend(destination, memberWithdrawalMessage, RocketmqSendCallbackBuilder.commonCallback());
		// 实际线下现金
		memberWithdrawApply.setRealMoney(StringUtils.isNotEmpty(num) ? Double.parseDouble(num) : 0);
		memberWithdrawApplyService.save(memberWithdrawApply);
		return memberWithdrawApply;
	}
	@Override
	public boolean close(String id) {
		Store store = this.getById(id);
		if (store != null) {
			store.setStoreDisable(StoreStatusEnum.CLOSED.value());
			// 下架所有此店铺商品
			goodsService.underStoreGoods(id);
			// Member member = memberService.getById(store.getMemberId());
			// 作废合伙人
			// partnerMapper.updateByMemberId(store.getMemberId());
			// 更新会员有店铺标识/可绑定状态
			// member.setHaveStore(false);
			// member.setExtensionFlag(Boolean.TRUE);
			// member.setStoreId(null);
			// memberService.updateById(member);
			// LambdaUpdateWrapper<Member> memberLambdaUpdateWrapper =
			// Wrappers.<Member>lambdaUpdate();
			// memberLambdaUpdateWrapper
			// .set(Member::getHaveStore, false).set(Member::getExtensionFlag, Boolean.TRUE)
			// .set(Member::getStoreId, null).eq(Member::getId, store.getMemberId());
			// memberService.update(memberLambdaUpdateWrapper);
			// 解绑与上级的关系;
			// List l = new ArrayList<>();
			// l.add(member.getId());
			// extensionService.updateBymemberId(l);
			// 更改店铺状态
			store.setStoreEndTime(new Date());
			boolean flag = this.updateById(store);
			return flag;
		}
		throw new ServiceException(ResultCode.STORE_NOT_EXIST);
	}

	@Override
	public boolean enable(String id) {
		Store store = this.getById(id);
		if (store != null) {
			store.setStoreDisable(StoreStatusEnum.OPEN.value());
			// 开启合伙人
			partnerMapper.updateOpenByMemberId(store.getMemberId());
			// 开启会员拥有店铺
			Member member = memberService.getById(store.getMemberId());
			member.setHaveStore(true);
			member.setExtensionFlag(Boolean.FALSE);
			member.setStoreId(store.getId());
			memberService.updateById(member);
			return this.updateById(store);
		}
		throw new ServiceException(ResultCode.STORE_NOT_EXIST);
	}

	@Override
	public boolean applyFirstStep(StoreCompanyDTO storeCompanyDTO) {
		// 获取当前操作的店铺
		Store store = getStoreByMember();
		// 如果没有申请过店铺，新增店铺
		if (!Optional.ofNullable(store).isPresent()) {
			AuthUser authUser = Objects.requireNonNull(UserContext.getCurrentUser());
			Member member = memberService.getById(authUser.getId());
			store = new Store(member);
			BeanUtil.copyProperties(storeCompanyDTO, store);
			this.save(store);
			StoreDetail storeDetail = new StoreDetail();
			storeDetail.setStoreId(store.getId());
			BeanUtil.copyProperties(storeCompanyDTO, storeDetail);
			return storeDetailService.save(storeDetail);
		} else {
			BeanUtil.copyProperties(storeCompanyDTO, store);
			this.updateById(store);
			// 判断是否存在店铺详情，如果没有则进行新建，如果存在则进行修改
			StoreDetail storeDetail = storeDetailService.getStoreDetail(store.getId());
			BeanUtil.copyProperties(storeCompanyDTO, storeDetail);
			return storeDetailService.updateById(storeDetail);
		}
	}

	@Override
	public boolean applySecondStep(StoreBankDTO storeBankDTO) {

		// 获取当前操作的店铺
		Store store = getStoreByMember();
		StoreDetail storeDetail = storeDetailService.getStoreDetail(store.getId());
		// 设置店铺的银行信息
		BeanUtil.copyProperties(storeBankDTO, storeDetail);
		return storeDetailService.updateById(storeDetail);
	}

	@Override
	public boolean applyThirdStep(StoreOtherInfoDTO storeOtherInfoDTO) {
		// 获取当前操作的店铺
		Store store = getStoreByMember();
		BeanUtil.copyProperties(storeOtherInfoDTO, store);
		this.updateById(store);

		StoreDetail storeDetail = storeDetailService.getStoreDetail(store.getId());
		// 设置店铺的其他信息
		BeanUtil.copyProperties(storeOtherInfoDTO, storeDetail);
		// 设置店铺经营范围
		storeDetail.setGoodsManagementCategory(storeOtherInfoDTO.getGoodsManagementCategory());
		// 最后一步申请，给予店铺设置库存预警默认值
		storeDetail.setStockWarning(10);
		// 修改店铺详细信息
		storeDetailService.updateById(storeDetail);
		// 设置店铺名称,修改店铺信息
		store.setStoreName(storeOtherInfoDTO.getStoreName());
		store.setStoreDisable(StoreStatusEnum.APPLYING.name());
		store.setStoreCenter(storeOtherInfoDTO.getStoreCenter());
		store.setStoreDesc(storeOtherInfoDTO.getStoreDesc());
		store.setStoreLogo(storeOtherInfoDTO.getStoreLogo());
		return this.updateById(store);
	}

	@Override
	public void updateStoreGoodsNum(String storeId) {
		// 获取店铺已上架已审核通过商品数量
		long goodsNum = goodsService.countStoreGoodsNum(storeId);
		// 修改店铺商品数量
		this.update(new LambdaUpdateWrapper<Store>().set(Store::getGoodsNum, goodsNum).eq(Store::getId, storeId));
	}

	@Override
	public void updateStoreCollectionNum(CollectionDTO collectionDTO) {
		baseMapper.updateCollection(collectionDTO.getId(), collectionDTO.getNum());
	}

	/**
	 * 获取当前登录操作的店铺
	 *
	 * @return 店铺信息
	 */
	@Override
	public Store getStoreByMember() {
		LambdaQueryWrapper<Store> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		if (UserContext.getCurrentUser() != null) {
			lambdaQueryWrapper.eq(Store::getMemberId, UserContext.getCurrentUser().getId());
			lambdaQueryWrapper.orderByDesc(Store::getCreateTime);
		}
		return this.getOne(lambdaQueryWrapper, false);
	}

	@Override
	public Store edit(Store store) {
		// 判断是否用户登录并且会员ID为当前登录会员ID
		AuthUser tokenUser = UserContext.getCurrentUser();
		if (tokenUser == null) {
			throw new ServiceException(ResultCode.USER_NOT_LOGIN);
		}
		this.updateById(store);
		return store;
	}

	@Override
	public IPage<StoreVO> pageByStoreVO(PageVO page, QueryWrapper<Store> storeQueryWrapper) {
		return baseMapper.pageByStoreVO(PageUtil.initPage(page), storeQueryWrapper);
	}

	@Override
	public StoreAddrDetailVO getAddressDetail() {
		AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
		StoreAddrDetailVO storeAddrDetailVO = this.baseMapper.getAddressDetail(currentUser.getStoreId());
		return storeAddrDetailVO;
	}

	@Override
	public GradeLevelVO findGradeLevel(String memberId) {
		return baseMapper.findGradeLevel(memberId);
	}

	@Override
	public Boolean updateRecommend(String storeId, Boolean recommend, int recommendRanking) {
		return this.baseMapper.updateRecommend(storeId, recommend, recommendRanking);
	}

	@Override
	public List<Category> getCategoryByPid(Long pid) {
		QueryWrapper<Category> queryWrapper = new QueryWrapper<Category>().eq("parent_id", pid).eq("delete_flag",
				false);
		return categoryMapper.selectList(queryWrapper);
	}

	@Override
	public IPage<StoreVO> firstTrial(StoreSearchParams storeSearchParams, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		if (StringUtils.isNotEmpty(currentUser.getMemberId())) {
			List<Member> agents = memberService.getAgents(currentUser.getMemberId());
			List<String> memberIds = new ArrayList<>();
			agents.forEach(item -> {
				if (item.getHaveStore()) {
					memberIds.add(item.getId());
				}
			});
			if (memberIds.size() > 0) {
				storeSearchParams.setMemberIds(memberIds);
			}
		}
		storeSearchParams.setOrderBySort(true);
		QueryWrapper queryWrapper = storeSearchParams.queryWrapper();
		// 根据code查询合伙人管理的区域Code
		if (StringUtils.isNotEmpty(storeSearchParams.getAdCode())) {
			List itemAdCod = regionService.getPartnerAdCode(storeSearchParams.getAdCode(), "4");
			queryWrapper.in("s.ad_code", itemAdCod);
		}
		return this.baseMapper.findByConditionPageShenhe(PageUtil.initPage(page), queryWrapper);
	}

	@Override
	public void updateStoreFreightTemplate() {
		List<FreightTemplate> list = freightTemplateService.list();
		List<String> storeIds = new ArrayList<>();
		list.forEach(item -> {
			storeIds.add(item.getStoreId());
		});
		List<StoreUser> StoreUsers = storeUserService.list(new QueryWrapper<StoreUser>().notIn("store_id", storeIds));
		StoreUsers.forEach(item -> {
			Store store = new Store();
			store.setId(item.getStoreId());
			this.saveFreightTemplate(store);
		});
	}

	@Override
	public void deleteByMemberId(String memberId) {
		this.baseMapper.deleteByMemberId(memberId);
	}
}
